% By: Carmen Guerra Garcia
% Date: March 27th 2019

%Description: This script reads a raw video file (.mov), extracts frames
%from it, determines corona as the region of maximum
%intensity and tracks total intensity 

 clear all
 close all
 clc
 
 load('background_correction03282019_bias.mat');

workingDir = tempname;
mkdir(workingDir);
mkdir(workingDir,'images');

filenames= {'03282019_wp3_PS16_3'};

for k=1

data = VideoReader([filenames{k} , '.mov']);

NN = data.NumberOfFrames;

for ii = 540:50:8100
    img = read(data,ii)-img_bk2;
    imwrite(img,fullfile(workingDir,'images',sprintf('img%d.jpg',ii)));
end
imageNames = dir(fullfile(workingDir,'images','*.jpg'));
imageNames = {imageNames.name}';

imageStrings = regexp([imageNames{:}],'(\d*)','match');
imageNumbers = str2double(imageStrings);
[~,sortedIndices] = sort(imageNumbers);
sortedImageNames = imageNames(sortedIndices);

for ii=1:length(sortedImageNames)
img = imread(fullfile(workingDir,'images',sortedImageNames{ii}));

Irr(ii) = sum(sum(img(580:630,600:1300,1),'omitnan'));

end

Nframe = [540:50:8100];

tt = Nframe./29.97./60; %min

plot(tt,Irr./max(Irr))

grid on

hold on

xlabel('Time [s]')
ylabel('Relative intensity [au]')

TU = [0.32 1.09 1.62 2.09 2.65 3.17 3.67 4.34];
U  = [0 10 20 25 30 35 40 45]';
Utxt = num2str(U);


IU(1:length(TU)) = nan;
for kk=1:length(TU)
IU(kk) = interp1(tt,Irr./max(Irr),TU(kk));
end

plot(TU,IU,'ro')
for kk=1:length(TU)
text(TU(kk)+0.1, IU(kk)+0.05, ['U=' Utxt(kk,1:2) 'm/s'] )
end

end














